package javase.javase02.networkprograming;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author: Gan
 * @date 2021/4/23 0023 16:53
 * @description:
 **/
public class NetworkUtils {
    public static DatagramPacket getSenderPacket(String targetIp, int port, String message) throws
            UnknownHostException {

        // 创建用于发送的数据报包
        byte[] bytes = message.getBytes();
        InetAddress ip = InetAddress.getByName(targetIp);
        DatagramPacket packet =
                new DatagramPacket(bytes, 0, bytes.length, ip, port);
        return packet;
    }

    // 创建用于接收的数据报包
    public static DatagramPacket getReceiverPacket() {
        byte[] bytes = new byte[1024];

        DatagramPacket packet =
                new DatagramPacket(bytes, 0, bytes.length);
        return packet;
    }

    // 解析数据
    public static String parsePacket(DatagramPacket packet){
        byte[] data = packet.getData();
        int offset = packet.getOffset();
        int length = packet.getLength();
        String s = new String(data, offset, length);
        //SocketAddress socketAddress = packet.getSocketAddress();
        return s;
    }
}
